package com.hitsoysauce.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ForceNoCacheFilter implements Filter {
    private static String[] excludeSuffixs = null; //例外的后缀

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig config) throws ServletException {
        String excludeSuffixStr = config.getInitParameter("excludeSuffixs");
        
        if (excludeSuffixStr != null && !excludeSuffixStr.equals("")) {
            excludeSuffixs = excludeSuffixStr.split(",");
            for (int i = 0; i < excludeSuffixs.length; i++) {
                excludeSuffixs[i] = ("." + excludeSuffixs[i]);
            }

        }
        
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {

    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {
        if (shouldNotFilter((HttpServletRequest) request)) {
            filterChain.doFilter(request, response);
            return;
        }
        ((HttpServletResponse) response).setHeader("Cache-Control", "no-cache");
        ((HttpServletResponse) response).setHeader("Pragma", "no-cache");
        ((HttpServletResponse) response).setDateHeader("Expires", -1);
        filterChain.doFilter(request, response);
    }

    /**
     * 根据后缀判断是否需要过滤
     * @param request
     * @return
     * @throws ServletException
     */
    protected boolean shouldNotFilter(HttpServletRequest request)
            throws ServletException {
        String path = request.getServletPath();

        for (String suffix : excludeSuffixs) {
            if (path.endsWith(suffix)) {
                return true;
            }
        }
        
        return false;
    }

}
